package com.cxx.home.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.cxx.framework.web.CustomException;
import com.cxx.home.dao.PasswordDao;
import com.cxx.home.dto.password.PasswordDto;
import com.cxx.home.entity.Password;
import com.cxx.home.mapper.PasswordMapper;
import com.cxx.home.service.PasswordService;
import com.cxx.home.vo.PasswordQueryVo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PasswordServiceImpl implements PasswordService {
    @Value("${aes.secret-key}")
    private String secretKey;

    @Resource
    private PasswordDao passwordDao;

    @Resource
    private PasswordMapper passwordMapper;

    @Override
    public Boolean add(PasswordDto passwordDto) {
        Password password = new Password();
        BeanUtils.copyProperties(passwordDto, password);
        password.setPassword(encryptPassword(passwordDto.getPassword()));

        return passwordMapper.insert(password) == 1;
    }

    @Override
    public Boolean update(Long id, PasswordDto passwordDto) {
        if (passwordMapper.selectById(id) == null) {
            throw new CustomException("该密码记录不存在");
        }

        Password password = new Password();
        BeanUtils.copyProperties(passwordDto, password);
        password.setId(id);
        password.setPassword(encryptPassword(passwordDto.getPassword()));
        return passwordMapper.updateById(password) == 1;
    }

    @Override
    public Boolean delete(Long id) {
        if (passwordMapper.selectById(id) == null) {
            throw new CustomException("该密码记录不存在");
        }

        return passwordMapper.deleteById(id) == 1;
    }

    @Override
    public List<PasswordDto> query(PasswordQueryVo query) {
        List<PasswordDto> passwordList = passwordDao.query(query);

        passwordList.forEach(item -> item.setPassword(decryptStr(item.getPassword())));
        return passwordList;
    }

    @Override
    public List<String > queryCategory() {
        return passwordDao.queryCategory();
    }

    private String encryptPassword(String password) {
        return SecureUtil.aes(secretKey.getBytes()).encryptBase64(password);
    }

    private String decryptStr(String password) {
        return SecureUtil.aes(secretKey.getBytes()).decryptStr(password);
    }
}
